package com.hugang.juc.test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 分治框架 fork join
 *
 * @author hg
 * @date 2020/9/1 19:42
 */
public class ForkjoinDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(123, 12312);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        System.out.println(forkJoinPool.getPoolSize());
        ForkJoinTask<Integer> submit = forkJoinPool.submit(myTask);

        Integer integer = submit.get();
        System.out.println(integer);
        forkJoinPool.shutdown();
    }

}

class MyTask extends RecursiveTask<Integer> {
    //标志位，当小于此标志时不用分治，否则分治
    public static final int FLAG = 10;
    private int start;
    private int end;
    private int result;

    public MyTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (end - start < FLAG) {
            for (int i = start; i <= end; i++) {
                result += i;
            }
        } else {
            int middle = (end + start) / 2;
            MyTask myTask1 = new MyTask(start, middle);
            MyTask myTask2 = new MyTask(middle + 1, end);
            myTask1.fork();
            myTask2.fork();
            result = myTask1.join() + myTask2.join();
        }
        return result;
    }
}
